package com.pic4493.app;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ppcodes.imageloader.core.DisplayImageOptions;
import com.ppcodes.imageloader.core.ImageLoader;
import com.ppcodes.imageloader.core.display.RoundedBitmapDisplayer;
import com.ppcodes.imageloader.utils.StorageUtils;
import com.ppcodes.slidingmenu.lib.SlidingMenu;
import com.pic4493.adapter.AdpGrid_Subscribe;
import com.pic4493.base.BaseUI;
import com.pic4493.comm.PubConst;
import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.ESubscribe;
import com.pic4493.net.NetClientJ;

import com.pic4493.utils.UtiDialog;
import com.pic4493.utils.UtiImage;
import com.pic4493.utils.UtiUI;

import android.os.Bundle;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class UIMain extends BaseUI implements View.OnClickListener
{
   /**
    * 用于判断是否是在其他页面登录,是的话在回到首页时,请刷新页面并且仅仅刷新一次,
    * 不能仅仅根据Session.getInstance().isLogin()来判断,会导致每次回到主页都重新加载
    * 参考onResume()方法,注销时设为false
    */
   private boolean isLogin = false;

   private DisplayImageOptions imgConfig;
   private DisplayImageOptions imgConfigHead;

   private ArrayList<ESubscribe> sList;

   // 右边按钮
   private ImageButton mBtnHead;
   // private ImageView mImgHead;
   private ImageView mImgSub;
   private ImageView mImgFav;
   private ImageView mImgOff;
   private ImageView mImgSet;
   private TextView mTxtNum;

   // 侧滑菜单
   private SlidingMenu mMenu;
   private LinearLayout mLayMenuLogoutBig;// 整个注销以后的框
   private LinearLayout mLayMenuLoginBig;// 整个登陆以后的框
   private LinearLayout mLayMenuLogin;// 登录按钮
   private LinearLayout mLayMenuLogout;// 注销按钮

   private ImageView mImgMenuSet;
   private ImageView mImgMenuHead;
   private TextView mTxtMenuName;
   private TextView mTxtMenuNum;
   private LinearLayout mLayMenuFav;
   private LinearLayout mLayMenuInfo;
   private LinearLayout mLayMenuSub;

   private LinearLayout mLayMenuOther;

   // 主界面
   private LinearLayout mLayWap;
   private LinearLayout mLayDay;
   private LinearLayout mLayLongClick;
   private LinearLayout mLayWallPaper;
   private GridView mGridView;
   private AdpGrid_Subscribe mAdpGrid;

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.uimain);
	  imgConfig = new DisplayImageOptions.Builder().cacheInMemory().cacheOnDisc().showStubImage(R.drawable.image_loading).showImageForEmptyUri(R.drawable.image_loading)
			.bitmapConfig(Bitmap.Config.RGB_565).build();
	  imgConfigHead = new DisplayImageOptions.Builder().cacheInMemory().cacheOnDisc().showStubImage(R.drawable.uimain_head).showImageForEmptyUri(R.drawable.uimain_head)
			.displayer(new RoundedBitmapDisplayer(UtiUI.dip2px(UIMain.this, 5))).bitmapConfig(Bitmap.Config.RGB_565).build();
	  initSlidingMenu();
	  initView();
	  initEvent();
	  initData();
   }

   private void initView()
   {
	  // 右边按钮
	  mBtnHead = (ImageButton) findViewById(R.id.uimain_btn_head);
	  mTxtNum = (TextView) findViewById(R.id.uimain_txt_num);
	  // mImgHead = (ImageView) findViewById(R.id.uimain_img_head);
	  mImgSub = (ImageView) findViewById(R.id.uimain_img_sub);
	  mImgFav = (ImageView) findViewById(R.id.uimain_img_fav);
	  mImgSet = (ImageView) findViewById(R.id.uimain_img_setting);
	  mImgOff = (ImageView) findViewById(R.id.uimain_img_offline);

	  // 侧滑菜单
	  mImgMenuHead = (ImageView) mMenu.findViewById(R.id.slidingmenu_img_head);
	  mImgMenuSet = (ImageView) mMenu.findViewById(R.id.slidingmenu_img_setting);
	  mLayMenuLoginBig = (LinearLayout) mMenu.findViewById(R.id.slidingmenu_lay_login_big);
	  mLayMenuLogoutBig = (LinearLayout) mMenu.findViewById(R.id.slidingmenu_lay_logout_big);
	  mLayMenuLogin = (LinearLayout) mMenu.findViewById(R.id.slidingmenu_lay_login);
	  mLayMenuLogout = (LinearLayout) mMenu.findViewById(R.id.slidingmenu_lay_logout);
	  mLayMenuFav = (LinearLayout) mMenu.findViewById(R.id.slidingmenu_lay_fav);
	  mLayMenuInfo = (LinearLayout) mMenu.findViewById(R.id.slidingmenu_lay_info);
	  mLayMenuSub = (LinearLayout) mMenu.findViewById(R.id.slidingmenu_lay_sub);
	  mTxtMenuName = (TextView) mMenu.findViewById(R.id.slidingmenu_txt_name);
	  mTxtMenuNum = (TextView) mMenu.findViewById(R.id.slidingmenu_txt_num);

	  // 主界面
	  mLayWap = (LinearLayout) findViewById(R.id.uimain_lay_wap);
	  mLayDay = (LinearLayout) findViewById(R.id.uimain_lay_day);
	  mLayWallPaper = (LinearLayout) findViewById(R.id.uimain_lay_wallpaper);
	  mLayLongClick = (LinearLayout) findViewById(R.id.uimain_lay_longclick);
	  mGridView = (GridView) findViewById(R.id.uimain_gv_list);

   }

   private void initEvent()
   {
	  // 右边按钮
	  mBtnHead.setOnClickListener(this);
	  // mImgHead.setOnClickListener(this);
	  mImgSub.setOnClickListener(this);
	  mImgFav.setOnClickListener(this);
	  mImgSet.setOnClickListener(this);
	  mImgOff.setOnClickListener(this);

	  // 侧滑菜单
	  mImgMenuHead.setOnClickListener(this);
	  mImgMenuSet.setOnClickListener(this);
	  mLayMenuFav.setOnClickListener(this);
	  mLayMenuInfo.setOnClickListener(this);
	  mLayMenuSub.setOnClickListener(this);
	  mLayMenuLogout.setOnClickListener(this);
	  mLayMenuLogin.setOnClickListener(this);

	  // 主界面
	  mLayWap.setOnClickListener(this);
	  mLayDay.setOnClickListener(this);

	  mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
	  {
		 @Override
		 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
		 {
			mAdpGrid.setIsDeleteMode();
			if (mAdpGrid.IsDeleteMode())
			{
			   mLayLongClick.setBackgroundResource(R.color.WhiteTransparent);
			}
			else
			{
			   mLayLongClick.setBackgroundDrawable(null);
			}
			return false;
		 }
	  });
	  mGridView.setOnTouchListener(new View.OnTouchListener()
	  {
		 @Override
		 public boolean onTouch(View v, MotionEvent event)
		 {
			int action = event.getAction();

			switch (action)
			{
			   case MotionEvent.ACTION_DOWN:
				  if (mAdpGrid.IsDeleteMode())
				  {
					 mAdpGrid.setIsDeleteMode(false);
					 mLayLongClick.setBackgroundDrawable(null);
				  }
				  break;
			}
			return false;
		 }
	  });
	  mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
	  {
		 @Override
		 public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		 {
			if (!mAdpGrid.IsDeleteMode())
			{
			   ESubscribe sub = (ESubscribe) mAdpGrid.getItem(position);
			   Intent uiIntent = new Intent();
			   if ("-1".equals(sub.getId()))// 手机站
			   {
				  uiIntent.setClass(UIMain.this, UIWap.class);
				  startActivity(uiIntent);
			   }
			   else if ("-2".equals(sub.getId()))// 每日新图
			   {
				  uiIntent.setClass(UIMain.this, UIEveryDay.class);
				  startActivity(uiIntent);
			   }
			   else if ("-3".equals(sub.getId()))// 订阅
			   {
				  uiIntent.setClass(UIMain.this, UISubscribe.class);
				  startActivityForResult(uiIntent, PubConst.ActivityJump.SUBSCRIBE);
			   }
			   else
			   {
				  uiIntent.setClass(UIMain.this, UIPicList.class);
				  uiIntent.putExtra(PubConst.Intent_Key.SubId, ((ESubscribe) mAdpGrid.getItem(position)).getId());
				  uiIntent.putExtra(PubConst.Intent_Key.Name, ((ESubscribe) mAdpGrid.getItem(position)).getName());
				  uiIntent.putExtra(PubConst.Intent_Key.Describe, ((ESubscribe) mAdpGrid.getItem(position)).getDescribe());
				  startActivity(uiIntent);
			   }
			}
		 }
	  });
   }

   /**
    * 检查缓存如果存在则证明需要更新壁纸,同时清除缓存
    */
   private void setWallPaper()
   {
	  if (Session.getInstance().picWallPaper != null)
	  {
		 if (mLayWallPaper != null)
		 {
			mLayWallPaper.setBackgroundDrawable(new BitmapDrawable(Session.getInstance().picWallPaper));
			Session.getInstance().picWallPaper = null;
		 }
	  }
   }

   private void initSlidingMenu()
   {
	  mMenu = new SlidingMenu(this);
	  mMenu.setMode(SlidingMenu.RIGHT);
	  mMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
	  mMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
	  mMenu.setFadeDegree(0.35f);
	  mMenu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);
	  mMenu.setMenu(R.layout.uimain_slidingmenu);
   }

   /**
    * 未登录显示默认数据,登录显示用户数据
    */
   private void initData()
   {
	  sList = getIntent().getParcelableArrayListExtra(PubConst.Intent_Key.Subscribes);
	  mAdpGrid = new AdpGrid_Subscribe(sList, mContext);
	  mGridView.setAdapter(null);
	  mGridView.setAdapter(mAdpGrid);
	  setLoginLayout();
   }

   /**
    * 刷新首页数据
    */
   private void refreshData()
   {
	  executeAsyncTask("refreshData");
   }

   @Override
   public void onClick(View v)
   {

	  Intent uiIntent = new Intent();
	  switch (v.getId())
	  {
		 case R.id.uimain_img_sub:// 订阅
			if (Session.getInstance().isLogin())
			{
			   uiIntent.setClass(UIMain.this, UISubscribe.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.SUBSCRIBE);
			}
			else
			{
			   uiIntent.setClass(UIMain.this, UISignUp.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			}

			break;
		 case R.id.uimain_img_fav:// 收藏
			if (Session.getInstance().isLogin())
			{
			   uiIntent.setClass(UIMain.this, UIFavorites.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.Favorite);
			}
			else
			{
			   uiIntent.setClass(UIMain.this, UISignUp.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			}

			break;
		 case R.id.uimain_img_offline:// 离线

			break;
		 case R.id.uimain_img_setting:// 设置
			uiIntent.setClass(UIMain.this, UISetting.class);
			startActivity(uiIntent);
			break;
		 case R.id.uimain_btn_head:// 头像
			if (Session.getInstance().isLogin())
			{
			   mMenu.showMenu();
			}
			else
			{
			   uiIntent.setClass(UIMain.this, UISignUp.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			}
			break;
		 case R.id.slidingmenu_img_setting:// 菜单_设置
			uiIntent.setClass(UIMain.this, UISetting.class);
			startActivity(uiIntent);
			break;
		 case R.id.slidingmenu_lay_fav:// 菜单_收藏
			if (Session.getInstance().isLogin())
			{
			   uiIntent.setClass(UIMain.this, UIFavorites.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.Favorite);
			}
			else
			{
			   uiIntent.setClass(UIMain.this, UISignUp.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			}
			break;
		 case R.id.slidingmenu_lay_info:// 菜单_消息
			uiIntent.setClass(UIMain.this, UIMessages.class);
			startActivity(uiIntent);
			break;
		 case R.id.slidingmenu_lay_login:// 菜单_登录
			uiIntent.setClass(UIMain.this, UISignUp.class);
			startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			break;
		 case R.id.slidingmenu_img_head:// 菜单_头像
			UtiImage.setFaceImage(UIMain.this);
			break;
		 case R.id.slidingmenu_lay_logout:// 菜单_注销
			logout();
			break;
		 case R.id.slidingmenu_lay_sub:// 菜单_订阅
			uiIntent.setClass(UIMain.this, UISubscribe.class);
			startActivityForResult(uiIntent, PubConst.ActivityJump.SUBSCRIBE);
			break;
	  }
   }

   /**
    * 根据登录状态设置侧边菜单
    * 
    * @param isLogin
    */
   private void setLoginLayout()
   {
	  if (Session.getInstance().isLogin())
	  {
		 mLayMenuLoginBig.setVisibility(View.GONE);
		 mLayMenuLogoutBig.setVisibility(View.VISIBLE);
		 if (Session.getInstance().getUser().getNewsCount() > 0)// 消息数
		 {
			mTxtNum.setVisibility(View.VISIBLE);
			mTxtMenuNum.setVisibility(View.VISIBLE);
			mTxtNum.setText(String.valueOf(Session.getInstance().getUser().getNewsCount()));
			mTxtMenuNum.setText(String.valueOf(Session.getInstance().getUser().getNewsCount()));
		 }
		 else
		 {
			mTxtNum.setVisibility(View.GONE);
			mTxtMenuNum.setVisibility(View.GONE);
		 }
		 mImgMenuHead.setVisibility(View.VISIBLE);
		 mTxtMenuName.setText(Session.getInstance().getUser().getNickName());
		 ImageLoader.getInstance().displayImage(Session.getInstance().getUser().getHeadImage(), mImgMenuHead, imgConfigHead);
		 ImageLoader.getInstance().displayImage(Session.getInstance().getUser().getHeadImage(), mBtnHead, imgConfigHead);
	  }
	  else
	  {
		 mLayMenuLoginBig.setVisibility(View.VISIBLE);
		 mLayMenuLogoutBig.setVisibility(View.GONE);
		 mTxtNum.setVisibility(View.GONE);
		 mTxtMenuName.setText("未登录");
		 mBtnHead.setImageResource(R.drawable.uimain_head);
		 mImgMenuHead.setVisibility(View.INVISIBLE);
		 mImgMenuHead.setImageResource(R.drawable.uimain_head);
	  }
   }

   private void logout()
   {
	  Session.getInstance().logout();
//	  initData();
	  isLogin = false;
	  executeAsyncTask("refreshData");
   }

   @Override
   protected void onResume()
   {
	  super.onResume();
	  if (mMenu != null)
	  {
		 if (mMenu.isMenuShowing())
		 {
			mMenu.showContent();
		 }
	  }
	  if (!isLogin && Session.getInstance().isLogin())
	  {
		 isLogin = true;
		 refreshData();
	  }
	  setWallPaper();
   }

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
	  if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
	  { // 按下的如果是BACK，同时没有重复

		 if (mMenu.isMenuShowing())
		 {
			mMenu.showContent();
		 }
		 else
		 {
			FinishDialog();
		 }
	  }
	  return false;
   }

   public void FinishDialog()
   {
	  DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
	  {
		 @Override
		 public void onClick(DialogInterface dialog, int which)
		 {
			dialog.dismiss();
			System.exit(0);
		 }
	  };
	  UtiDialog.getInstance().ShowOKCancelAlertDialog(UIMain.this, "提示", "您打算退出程序吗？", listener);
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data)
   {
	  if (resultCode == RESULT_OK)
	  {
		 if (requestCode == PubConst.ActivityJump.SUBSCRIBE)// 订阅更改
		 {
			refreshData();
		 }

		 // 设置头像=======================================================================================
		 switch (requestCode)
		 {
			case UtiImage.LOCAL_IMAGE_REQUEST_CODE:
			   UtiImage.cropPhoto(UIMain.this, data.getData(), 350, 350, UtiImage.RESULT_REQUEST_CODE);
			   break;
			case UtiImage.CAMERA_REQUEST_CODE:
			   UtiImage.cropPhoto(UIMain.this, data.getData(), 350, 350, UtiImage.RESULT_REQUEST_CODE);
			   break;
			case UtiImage.RESULT_REQUEST_CODE:
			   if (data != null)
			   {
				  getImageToView(data);
			   }
			   break;
		 }
	  }
   }

   /**
    * 保存裁剪之后的图片数据
    * 
    * @param picdata
    */
   private void getImageToView(Intent data)
   {
	  Bundle extras = data.getExtras();
	  if (extras != null)
	  {
		 Bitmap photo = extras.getParcelable("data");
		 try
		 {
			File file = new File(StorageUtils.getCacheDirectory(UIMain.this), UtiImage.IMAGE_HEAD_NAME);
			UtiImage.saveFaceBitmap(photo);
			byte[] str = UtiImage.readFileToByte(file, UtiImage.DEFAULT_ENCODING);
			// String str=UtiImage.readFileToString(file,
			// UtiImage.DEFAULT_ENCODING);
			// String str = new
			// String(UtiImage.saveFaceBitmap(UIMain.this,photo), "UTF-8");
			// String str = new String(UtiImage.getBytes(photo));
			// String str=new String(UtiImage.toByteArray(file),"UTF-8");
			// String str=UtiImage.saveFaceBitmap(UIMain.this, photo);
			executeAsyncTask("upload", new Object[] { str, photo });
		 }
		 catch (Exception e)
		 {
			Log.d("ERROR", "UIMain_getImageToView(data) " + e);
		 }
	  }
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  UtiDialog.getInstance().ShowLoadingDialogNoTitleEX(UIMain.this, "加载数据请稍候....");
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if (taskName != null)
	  {
		 if (taskName.equals("refreshData"))
		 {
			return NetClientJ.GetHomeSubscribes();
		 }
		 else if ("upload".equals(taskName))
		 {
			// return NetClientJ.UploadFaceImage(params[0].toString());
			return NetClientJ.sendPic((byte[]) params[0]);
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  UtiDialog.getInstance().DismissLoadingDialog();
	  try
	  {
		 if (result != null)
		 {
			DJson data = (DJson) result;
			if (!data.getHead().hasError())
			{
			   if (taskName.equals("refreshData"))
			   {
				  JSONObject object = data.getBody();
				  JSONArray subscibes = object.optJSONArray("subscibe");

				  ESubscribe sub = null;
				  sList = new ArrayList<ESubscribe>();
				  sub = new ESubscribe();
				  sub.setCanDelete(false);
				  sub.setCover(object.optString("wap_image"));
				  sub.setName("手机网站");
				  sub.setId("-1");
				  sList.add(sub);
				  sub = new ESubscribe();
				  sub.setCanDelete(false);
				  sub.setCover(object.optString("new_image"));
				  sub.setName("每日新图");
				  sub.setId("-2");
				  sList.add(sub);
				  if (subscibes != null)
				  {
					 for (int i = 0; i < subscibes.length(); i++)
					 {
						sub = new ESubscribe();
						sub.setCover(subscibes.optJSONObject(i).optString("ztcover"));
						sub.setId(subscibes.optJSONObject(i).optString("sid"));
						sub.setName(subscibes.optJSONObject(i).optString("ztname"));
						sub.setDescribe(subscibes.optJSONObject(i).optString("describe"));
						sub.setCanDelete(true);
						sList.add(sub);
					 }
				  }
				  if (Session.getInstance().isLogin())
				  {
					 sub = new ESubscribe();
					 sub.setCanDelete(false);
					 sub.setId("-3");
					 sList.add(sub);
				  }

				  mAdpGrid = new AdpGrid_Subscribe(sList, mContext);
				  mGridView.setAdapter(null);
				  mGridView.setAdapter(mAdpGrid);
				  setLoginLayout();
			   }
			   else if ("upload".equals(taskName))
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "上传成功");
				  mImgMenuHead.setImageBitmap((Bitmap) params[1]);
				  mBtnHead.setImageBitmap((Bitmap) params[1]);
			   }
			}
			else
			{
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, data.getHead().getRspMsg());
			}
		 }
		 else
		 {
			UtiDialog.getInstance().ShowToastInfoShort(mContext, "网络异常请稍候再试");
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIMain_onAsyncTaskEnd(taskId, taskName, params, result) " + e);
	  }
   }

}
